import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:liuxlcommon/lget/lget.dart';
import 'package:liuxlcommon/view/loading_view.dart';
import 'package:liuxlcommon/view/lxl_widget.dart';
import 'package:liuxlcommon/view/my_box.dart';
import 'package:liuxlcommon/view/my_style.dart';
import 'package:love_newf/app/com/base/base_state.dart';
import 'package:love_newf/app/com/model/friend_user_info_model.dart';
import 'package:love_newf/app/com/view/base_column.dart';
import 'package:love_newf/app/page/chat/caht_loading_view.dart';
import 'package:love_newf/generated/assets.dart';
import 'package:love_newf/value/app_colors.dart';
import 'package:love_newf/value/app_const.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_message.dart';

import 'chat_logic.dart';

class ChatPage extends StatefulWidget {
  const ChatPage({super.key});

  static openPage(userId, {FriendUserInfoModel? friendUserInfo}) {
    if (friendUserInfo != null) {
      Get.to(const ChatPage(), arguments: friendUserInfo.toJson());
    }
  }

  @override
  State<ChatPage> createState() => _ChatPageState();
}

class _ChatPageState extends BaseState<ChatPage, ChatLogic> {
  @override
  get initData {
    resizeToAvoidBottomInset = true;
    logic.friendUserInfo = FriendUserInfoModel.fromJson(Get.arguments);
    title = logic.friendUserInfo.nick;
  }

  @override
  Widget get easyBody => LColumn.eazy([LExpand(child: chatList), sendInputBox])
      .onTapDown((d) => OldLInput.unfocus());

  get chatList => CahtLoadingView(
      datas: logic.datas,
      scrollController: logic.scrollController,
      itemCall: (context, position) => itemView(position),
      isPullUp: false,
      isPullDown: true,
      onStateClick: (type) {
        if ((logic.datas?.length ?? 0) == 0) logic.datas = null;
        logic.update();
      },
      onLoad: (type) async {
        if (type == 1) {
          logic.pageNum = 1;
        } else if (type == 2) {
          logic.pageNum++;
        }
        return await logic.getData();
      },
      onSuccess: () {
        if (logic.datas != null) logic.update();
      });

  get sendInputBox => LColumn.eazy([
        LRow.eazy([
          11.lsw,
          LInput(
            logic.message,
            lStyle: LStyle(
                alignment: Alignment.centerLeft,
                flex: 1,
                fontSize: 14.sp,
                backgroundColor: Color(0xFFF5F3F6),
                radius: 19.w,
                hintColor: AppColors.textHintColor,
                padding: EdgeInsets.symmetric(horizontal: 15.w, vertical: 9.w),
                hintText: '请输入消息...'),
            onChanged: (text) {
              logic.message = text;
            },
            onSubmitted: (text) {
              logic.message = text;
              logic.sendMessage();
            },
          ),
          8.lsw,
          LText.easy("发送", 16.w, fw4, Colors.white)
              .size(76.w, 38.w)
              .center()
              .radius(19.w)
              .bgColor(const Color(0xFFFF4665))
              .onTapL(() {
            logic.sendMessage();
          }),
          11.lsw
        ]),
        LRow.eazy([
          LImage.easy(Assets.messageChatImage, 50.w, 50.w).paddingAll(10.w),
          LImage.easy(Assets.messageChatGift, 50.w, 50.w).paddingAll(7.w),
          LImage.easy(Assets.messageChatPhone, 50.w, 50.w).paddingAll(10.w),
          10.lsw
        ]).center()
      ])
          .padding(top: 7.w, bottom: LGet.bottomPadding(context))
          .bgColor(Colors.white);

  itemView(int position) {
    V2TimMessage message = logic.showDatas![position];
    int timestamp = message.timestamp ?? 0; // 示例时间戳，单位为毫秒
    DateTime dateTime = DateTime.fromMillisecondsSinceEpoch(timestamp);
    // 格式化日期时间
    String formattedDate = DateFormat('MM-dd HH:mm:ss').format(dateTime);

    return LColumn.eazy([
      16.lsh,
      LText.easy(formattedDate, 12.w, fw4, const Color(0xFF818181)),
      11.lsh,
      LRow.eazy(content(message)).align(Alignment.topLeft).padding(left: 11.w)
    ]).bgColor(Colors.white);
  }

  List<Widget> content(V2TimMessage message) {
    List<Widget> content = [];
    if (message.isSelf ?? false) {
      content.add(60.lsw);
      content.add(LExpand(
          child:
              LText.easy(message.textElem?.text ?? "", 14.w, null, Colors.white)
                  .bgColor(const Color(0xFFFF4665))
                  .radius(8.w)
                  .padding(left: 11.w, right: 11.w, top: 8.w, bottom: 8.w)));
      content.add(10.lsw);
      content.add(LImage.easy(message.faceUrl, 46.w, 46.w, 46.w));
      content.add(11.lsw);
    } else {
      content.add(LImage.easy(message.faceUrl, 46.w, 46.w, 46.w));
      content.add(10.lsw);
      content.add(LText.easy(message.textElem?.text ?? "", 14.w)
          .flex(1)
          .bgColor(const Color(0xFFF7F8FA))
          .radius(8.w)
          .padding(left: 11.w, right: 11.w, top: 8.w, bottom: 8.w));
      content.add(60.lsw);
    }
    return content;
  }
}
